<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';

/**
 * CFD API接口（微信）
 *
 * @package         CodeIgniter
 * @subpackage      Rest Server
 * @category        Controller
 * @author          Phil Sturgeon, Chris Kacerguis
 * @license         MIT
 * @link            https://github.com/chriskacerguis/codeigniter-restserver
 */
class Cfd extends REST_Controller {
	private $productConfig;
	private $user_info;

	public function __construct(){  
        parent::__construct();
        $this->load->config('cfd');
        //加载通行证类
        $this->load->library('passPort');
        $this->passportClass = $this->passport;
        
        $this->passportClass->setPlatform($this->config->item('platform'));//设置平台
		$this->user_info = $this->passportClass->checkCookieAuthCode('','',true);
		if(empty($this->user_info)){
			$this->response(array(
                $this->config->item('rest_status_field_name') => 200001,
                $this->config->item('rest_message_field_name') => '请先登陆'
            ), REST_Controller::HTTP_OK);
		}
    }

    public function ajaxTrade_get(){
    	$get = $this->get();
    	$pid = $get['pid'];
    	$action = $get['action'];
    	//获取产品详细信息
		$this->load->model('product_model');
		$productData = $this->product_model->getProduct(array('pid'=>$pid, 'status'=>1),1);
		if(empty($productData)){
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100001,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		//加载CFD操作类
		$this->load->library('cfdClass');
		if(!$this->cfdclass->setProduct($productData['name'],'IB')){//设置产品
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100002,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		$cfdConfig = $this->cfdclass->getCfdConfig();
		$assign['ticket'] = $this->user_info['ticket'];
		$assign['pid'] = $pid;
		$assign['action'] = $action;
		$assign['name'] = $productData['name'];
		$assign['desc'] = $productData['desc'];
		$assign['index'] = $cfdConfig[$productData['name']]['cny']['index'];
		$bs = ($action=='bid')?'ask':'bid';
		// $assign['priceKey'] = $productData['name']."_".strtoupper($bs)."_PRICE";
		$assign['priceKey'] = $productData['name']."_LAST_PRICE";
		$assign['comKey'] = $productData['name']."_".$action."_com";
    	$this->load->view('cfd/ajaxTrade',$assign);
    }

    /**
     * 交易相关操作
     */
    public function trade_post(){
    	$post = $this->post();
        if(empty($post)) {
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100001,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
        }
        $pid = $post['pid'];
        //获取产品详细信息
		$this->load->model('product_model');
		$productData = $this->product_model->getProduct(array('pid'=>$pid, 'status'=>1),1);
		if(empty($productData)){
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100001,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		//加载CFD操作类
		$this->load->library('cfdClass');
		if(!$this->cfdclass->setProduct($productData['name'],'IB')){//设置产品
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100002,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
        $action = isset($post['action'])?$post['action']:NULL; // *Require
		if(in_array($action,array('bid','ask','bid_ping','ask_ping','stop_lose'))){
			if(!$this->checkTime() || !$this->checkFlag()) {
				$this->response(array(
	                $this->config->item('rest_status_field_name') => 999999,
	                $this->config->item('rest_message_field_name') => '不在交易时段'
	            ), REST_Controller::HTTP_OK);
			}
			//if($this->checkStop()) jsonReturn(-1,"停止交易"); // 停止交易
		}
		switch ($action) {
			case 'bid': // 买多开仓
			case 'ask': // 卖空开仓
				$this->open($post);
				break;
			case 'bid_ping': // 买多平仓
			case 'ask_ping': // 卖空平仓
				$this->close($post);
				break;
			case 'stop_lose': // 设置止损 
				$this->stopLose($post);
				break;
			default:
				$this->response(array(
	                $this->config->item('rest_status_field_name') => 100002,
	                $this->config->item('rest_message_field_name') => '无效请求'
	            ), REST_Controller::HTTP_OK);
		}
    }

    public function ajax_get(){
    	$get = $this->get();
    	$action = isset($get['action'])?$get['action']:NULL; // *Require
		switch ($action) {
			case 'position': //获取持仓信息
				$this->position($get);
				break;
			default:
				$this->response(array(
	                $this->config->item('rest_status_field_name') => 100002,
	                $this->config->item('rest_message_field_name') => '无效请求'
	            ), REST_Controller::HTTP_OK);
		}
    }

    /**
	 * 开仓操作
	 * @return [type] [description]
	 */
	private function open($post){
		$pid = $post['pid'];//产品id
		$dtype = $post['dtype'];//计价方式
		$action = $post['action'];//bid买多开仓 ask卖空开仓 bid_ping买多平仓 ask_ping卖空平仓
		$com = $post['com'];//佣金限制-开仓（判断下单时和成交时是否相差太大，太大则撤单）
		$type = 0;//0市价 1限价
		$times = 10;//每手交易保证金
		$price = 0;//0市价，其他限价
		$num = $post['num'];//默认数量为1张
		if($dtype == 'ticket'){//体验券
			// $num = 1;
		}
		if(!in_array($pid,$this->config->item('pids'))){
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100003,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		//获取产品详细信息
		$this->load->model('product_model');
		$productData = $this->product_model->getProduct(array('pid'=>$pid, 'status'=>1),1);
		if(empty($productData)){
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100004,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		//加载CFD操作类
		$this->load->library('cfdClass');
		if(!$this->cfdclass->setProduct($productData['name'],'IB')){//设置产品
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100005,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		if(!$this->cfdclass->setDenom($dtype)){//设置计价方式
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100006,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		$denomConfig = $this->cfdclass->getDenomConfig();
		if(!in_array($times,$denomConfig['times'])){
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100007,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		if($num>$denomConfig['open_max']){
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100008,
                $this->config->item('rest_message_field_name') => '数量不能超过'.$denomConfig['open_max'].'手'
            ), REST_Controller::HTTP_OK);
		}


		//链接redis
        $this->load->driver('cache');
        $this->cache->redis->is_supported();
        $platform = $this->config->item('platform');//平台
        $delayKey = "$platform|openDelay|".$this->user_info['uid'];
        $flag = $this->cache->redis->getClient()->get($delayKey);
        if($flag==1){
        	$this->response(array(
                $this->config->item('rest_status_field_name') => 100009,
                $this->config->item('rest_message_field_name') => '交易冷却5秒,请稍后再试'
            ), REST_Controller::HTTP_OK);
        }

		$data = array(
			'uid' => $this->user_info['uid'],
			'pid' => $pid,
			'dtype' => $dtype,
			'type' => $type,
			'times' => $times,
			'action' => $action,
			'price' => $price,
			'num' => $num,
			'com' => $com,
		);
		$rs = $this->cfdclass->open($data);
		$rs = json_decode($rs,true);
		if($rs['errno']==0){
			$this->cache->redis->getClient()->set($delayKey,1);
			$this->cache->redis->getClient()->expire($delayKey,5);
			$this->response(array(
				$this->config->item('rest_status_field_name')=>0,
				'orderno'=>$rs['data']['orderno']
			), REST_Controller::HTTP_OK);
		}else{
			$this->response(array(
                $this->config->item('rest_status_field_name') => $rs['errno'],
                $this->config->item('rest_message_field_name') => $rs['msg']
            ), REST_Controller::HTTP_OK);
		}
	}


	/**
	 * 平仓操作
	 * @return [type] [description]
	 */
	private function close($post){
		$posid = $post['posid'];//持仓id
		$pid = $post['pid'];//产品id
		$dtype = $post['dtype'];//计价方式
		$action = $post['action'];//bid买多开仓 ask卖空开仓 bid_ping买多平仓 ask_ping卖空平仓
		$type = 0;//0市价 1限价
		$times = 10;//每手交易保证金
		$price = 0;//0市价，其他限价
		$num = 'all';//默认数量为全部

		if(!in_array($pid,$this->config->item('pids'))){
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100003,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		//获取产品详细信息
		$this->load->model('product_model');
		$productData = $this->product_model->getProduct(array('pid'=>$pid, 'status'=>1),1);
		if(empty($productData)){
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100004,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		//加载CFD操作类
		$this->load->library('cfdClass');
		if(!$this->cfdclass->setProduct($productData['name'],'IB')){//设置产品
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100005,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		if(!$this->cfdclass->setDenom($dtype)){//设置计价方式
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100006,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		$denomConfig = $this->cfdclass->getDenomConfig();
		if(!in_array($times,$denomConfig['times'])){
			$this->response(array(
                $this->config->item('rest_status_field_name') => 100007,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
		}
		$data = array(
			'uid' => $this->user_info['uid'],
			'posid' => $posid,
			'pid' => $pid,
			'dtype' => $dtype,
			'type' => $type,
			'times' => $times,
			'action' => $action,
			'price' => $price,
			'num' => $num,
		);
		$rs = $this->cfdclass->close($data);
		$rs = json_decode($rs,true);
		if($rs['errno']==0){
			$this->response(array(
				$this->config->item('rest_status_field_name')=>0,
				'orderno'=>$rs['data']['orderno']
			), REST_Controller::HTTP_OK);
		}else{
			$this->response(array(
                $this->config->item('rest_status_field_name') => $rs['errno'],
                $this->config->item('rest_message_field_name') => $rs['msg']
            ), REST_Controller::HTTP_OK);
		}
	}

	/**
	 * 获取持仓信息
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	private function position($data){
		$name = $data['name'];
		$uid = $this->user_info['uid'];
		//加载CFD操作类
		$this->load->library('cfdClass');
		//获取持仓信息
		$this->load->model('cfd_model');
		$positionArr = array();
		$zyk = 0;//总盈亏
		$net = 0;
		$direction = '';
		$positionList = $this->cfd_model->getPosition(array('uid'=>$uid,'name'=>$name,'flag'=>0),'all','name DESC, format DESC');
		if(!empty($positionList)){ 
			foreach($positionList as &$position){
				if(!$this->cfdclass->setProduct($position['name'],'IB')){//设置产品
					continue;
				}
				if(!$this->cfdclass->setDenom($position['dtype'])){//设置计价方式
					continue;
				}
				$redisData = $this->cfdclass->redisAllData();
				$lastest_price = isset($redisData['trade']['LAST_PRICE']) ? $redisData['trade']['LAST_PRICE'] : 0;
				$position['total'] = bcadd($position['num'],$position['block_num']);
				$position['margin'] = del0($this->cfdclass->countBZJ($position['total'], $position['times'], $position['additional']));
				// echo $lastest_price.",".$position['price'].",".$position['total'].",".$position['bs'].",".$position['commission'].",".$position['overnight'];
				// echo "<br>";
				$position['yk'] = del0($this->cfdclass->countYK($lastest_price,$position['price'],$position['total'],$position['bs'],$position['commission'],$position['overnight']));
				$position['ykl'] = $this->cfdclass->countYKL($position['yk'], $position['margin']);
				$position['fee'] = $this->cfdclass->countTotalFee(bcadd($position['commission'],$position['overnight'],8),$position['total']);
				$zyk = bcadd($zyk,$position['yk'],2);
				if($position['bs']=='bid'){
					$tmpNet = $position['total'];
				}else{
					$tmpNet = bcmul($position['total'],-1,0);
				}
				$net = bcadd($net,$tmpNet,0);
				if($net>0){
					$direction = "买涨";
				}else if ($net<0) {
					$direction = "买跌";
				}
				$positionArr[] = array(
					'id' => $position['id'],
					'dtype' => $position['dtype'],
					'price' => del0($position['price']),
					'num' => $position['num'],
					'bs' => $position['bs'],
					'yk' => del0($position['yk']),
				);
			}
			$productData = $this->cfdclass->getProductData();
			$dst = $this->cfdclass->checkDST($position['name']);
			$settlementArr = explode(',',$productData['settlement']);
			$this->response(array(
				$this->config->item('rest_status_field_name') => 0,
				'pid' => $productData['pid'],
				'name' => $position['name'],
				'settlement' => $settlementArr[$dst],
				'desc' => $productData['desc'],
				'data' => $positionArr,
				'zyk' => del0($zyk),
				'net' => $net,
				'direction' => $direction,
				'isEmpty'=> 0,
			), REST_Controller::HTTP_OK);
		}else{
			$this->response(array(
				$this->config->item('rest_status_field_name') => 0,
				'name' => $name,
				'isEmpty'=> 1,
			), REST_Controller::HTTP_OK);
		}

	}

	 /**
	 * 检查是否在交易时间内
	 * @return boolean
	 */
	private function checkTime() {
		$rs = $this->cfdclass->checkTime();
		return $rs;
	}

	/**
	 * TODO: 需要设置FLAG参数
	 */
    public function checkFlag(){
        $tradeData = $this->cfdclass->redisAllData();
        if($tradeData['trade']['FLAG']==0){//不能交易
        	// return false;
        }
        return true;
	}


}
